package com.ruoyi.api.dailyWork.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.mqtt.MqttService;
import com.ruoyi.api.wsmessage.domain.Wsmessage;
import com.ruoyi.redis.RedisService;
import com.ruoyi.result.ResultEnum;
import com.ruoyi.result.ResultView;
import com.ruoyi.system.cache.user.UserCacheService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Author: LvKinfy
 * Time: 17:35
 * Desc: 日报相关接口
 */
@RestController
@RequestMapping("/api/dailywork")
public class DailyWorkController {
  @Value("${wspaas.dailyworkUrl}")
  private String dwUrl;
  @Autowired
  private MqttService mqttService;
  @Autowired
  private RedisService redisService;
  @Autowired
  private UserCacheService userCacheService;

  //增加审批意见
  @PostMapping("/{service}/approve/{id}")
  private Object reCommit(@PathVariable String service, @PathVariable String id, @RequestBody JSONObject o) throws Exception {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    String roles = null;
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/");
    if ("am".equalsIgnoreCase(service) || "pm".equalsIgnoreCase(service)) {
      sb.append("driver/");
      roles = "driver";
    } else {
      roles = "other";
    }
    sb.append(service).append("/approve/").append(id);
    String s = HttpClientUtil.doPost(sb.toString(), o);
    if (!"-1".equalsIgnoreCase(s)) {
      JSONObject jsonObject = JSONObject.parseObject(s);
      Integer code = jsonObject.getInteger("code");
      if (code != 200) return ResultView.error(ResultEnum.OPR_FAILED);
      //异常提交更新的时候，判断异常更新的发起人，异常更新者
      String approveId = o.getString("approveId");
      String approveName = o.getString("approveName");
      String createrId = o.getString("createrId");
      SysUser user = userCacheService.getUserInfo(Long.parseLong(createrId));
      String entityId = jsonObject.getString("data");
      String typeName = "异常日报";
      String type = service;
      String permisson=null;
      if(o.get("state")!=null){
        permisson=String.valueOf(o.get("state"));
      }
      String title = approveName + " 跟进了异常信息" + entityId;


      Wsmessage wsmessage=new Wsmessage();
      wsmessage.setUserSenderId(user.getUserId());
      wsmessage.setRole(roles);
      wsmessage.setType(service);
      wsmessage.setTypeName(typeName);
      wsmessage.setTitle(title);
      wsmessage.setEntityId(entityId);
      wsmessage.setPermission(permisson);
      wsmessage.setSubmitTime(new Date());
      if (approveId == null || (approveId != null && createrId != null && approveId.equalsIgnoreCase("createrId"))) {
        if (user != null) {
          //表示当前编辑者是异常发起人，那么要推消息给管理
          mqttService.sendMessage(2,wsmessage);
        }
      } else {
        if (user != null) {
          //表示当前编辑者是管理者发起人，那么要推消息给发起人
          mqttService.sendMessage(1,wsmessage);
        }
      }
      return s;
    }
    return ResultView.error(ResultEnum.CODE_2);
  }

  //局部更新
  @PostMapping("/{service}/update/{id}")
  private Object updateById(@PathVariable String service,@PathVariable String id, @RequestBody JSONObject o) {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/");
    if ("am".equalsIgnoreCase(service) || "pm".equalsIgnoreCase(service)|| "report".equalsIgnoreCase(service)) {
      sb.append("driver/");
    }
    sb.append(service).append("/update/").append(id);
    return HttpClientUtil.doPost(sb.toString(), o);
  }

  //异常跟踪日报列表
  @GetMapping("/{service}/findFollowList")
  private Object getFollowList(@PathVariable String service, String role, String uid, String state, String suspendstate) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/");
    if (null != role) {
      sb.append(role).append("/");
    }
    sb.append(service).append("/findFollowList/").append(uid).append("/").append(state).append("/").append(suspendstate);
    return HttpClientUtil.doGet(sb.toString());
  }

  //实时登记
  @PostMapping("/report/{roles}/commit")
  private Object reCommit(@PathVariable String roles, @RequestBody JSONObject o) throws Exception {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    //计算出行驶公里数
    Long mileage = o.getLong("startMileage");
    if (null != mileage) {
      Object latestMileage = redisService.getAndset(o.getString("plateNo"), mileage);
      if (null != latestMileage) {
        o.put("mileage", mileage - Long.parseLong(String.valueOf(latestMileage)));
      }
    }

    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/report/commit");
    String s = HttpClientUtil.doPost(sb.toString(), o);
    if (!"-1".equalsIgnoreCase(s)) {
      JSONObject jsonObject = JSONObject.parseObject(s);
      Integer code = jsonObject.getInteger("code");
      if (code != 200) return ResultView.error(ResultEnum.OPR_FAILED);
      String entityId = jsonObject.getString("data");

      String userName = o.getString("createrName");
      String type = "driverreport";//项目部日报
      String typeName = "实时登记";
      String title = userName + "实时登记";
      String userId = String.valueOf(o.get("createrId"));
      SysUser user = userCacheService.getUserInfo(Long.parseLong(userId));
      Object obj=jsonObject.get("state");
      String permission=null;
      if(obj !=null){
        typeName = "异常日报";
        permission=String.valueOf(obj);
      }

      Wsmessage wsmessage=new Wsmessage();
      wsmessage.setUserSenderId(user.getUserId());
      wsmessage.setRole(roles);
      wsmessage.setType("driverreport");
      wsmessage.setTypeName(typeName);
      wsmessage.setTitle(title);
      wsmessage.setEntityId(entityId);
      wsmessage.setPermission("");
      wsmessage.setSubmitTime(new Date());
      mqttService.sendMessage(1, wsmessage);

      return s;
    }
    return ResultView.error(ResultEnum.CODE_2);
  }

  //上班日报提交
  @PostMapping("/am/{roles}/commit")
  private Object amCommit(@PathVariable String roles, @RequestBody JSONObject o) throws Exception {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    //计算出行驶公里数
    Long mileage = o.getLong("startMileage");
    if (null != mileage) {
      Object latestMileage = redisService.getAndset(o.getString("plateNo"), mileage);
      if (null != latestMileage) {
        o.put("mileage", mileage - Long.parseLong(String.valueOf(latestMileage)));
      }
    }

    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/am/commit");

    String s = HttpClientUtil.doPost(sb.toString(), o);

    if (!"-1".equalsIgnoreCase(s)) {
      JSONObject jsonObject = JSONObject.parseObject(s);
      String typeName = "上班日报";
      String permission=null;
      Object obj=jsonObject.get("state");
      if(obj !=null){
        typeName = "异常日报";
         permission=String.valueOf(obj);
      }
      String entityId = jsonObject.getString("data");
      String userName = o.getString("createrName");
      String type = "am";//项目部日报
      String title = userName + "上班日报";
      String userId = String.valueOf(o.get("createrId"));
      SysUser user = userCacheService.getUserInfo(Long.parseLong(userId));

      Wsmessage wsmessage=new Wsmessage();
      wsmessage.setUserSenderId(user.getUserId());
      wsmessage.setRole(roles);
      wsmessage.setType("am");
      wsmessage.setTypeName(typeName);
      wsmessage.setTitle(title);
      wsmessage.setEntityId(entityId);
      wsmessage.setPermission("");
      wsmessage.setSubmitTime(new Date());
      wsmessage.setSubmitTime(new Date());
      mqttService.sendMessage(1, wsmessage);
      return s;
    }
    return ResultView.error(ResultEnum.CODE_2);
  }

  //下班日报提交
  @PostMapping("/pm/{roles}/commit")
  private Object pmCommit(@PathVariable String roles, @RequestBody JSONObject o) throws Exception {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    //计算出行驶公里数
    Long mileage = o.getLong("startMileage");
    if (null != mileage) {
      Object latestMileage = redisService.getAndset(o.getString("plateNo"), mileage);
      if (null != latestMileage) {
        o.put("mileage", mileage - Long.parseLong(String.valueOf(latestMileage)));
      }
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/pm/commit");
    String s = HttpClientUtil.doPost(sb.toString(), o);
    if (!"-1".equalsIgnoreCase(s)) {
      JSONObject jsonObject = JSONObject.parseObject(s);
      String entityId = jsonObject.getString("data");
      String typeName = "下班日报";
      Object obj=jsonObject.get("state");
      String permission=null;
      if(obj !=null){
        typeName = "异常日报";
         permission=String.valueOf(obj);
      }
      String userName = o.getString("createrName");
      String type = "pm";//日报消息
      String title = userName + "下班日报";
      String userId = String.valueOf(o.get("createrId"));
      SysUser user = userCacheService.getUserInfo(Long.parseLong(userId));

      Wsmessage wsmessage=new Wsmessage();
      wsmessage.setUserSenderId(user.getUserId());
      wsmessage.setRole(roles);
      wsmessage.setType("am");
      wsmessage.setTypeName(typeName);
      wsmessage.setTitle(title);
      wsmessage.setEntityId(entityId);
      wsmessage.setPermission("");
      wsmessage.setSubmitTime(new Date());
      mqttService.sendMessage(1, wsmessage);

      return s;
    }
    return ResultView.error(ResultEnum.CODE_2);
  }


  @PostMapping("/report/detail/{roles}/{id}")
  private Object redetail(@PathVariable String roles, @PathVariable String id) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/report/detail/").append(id);
    return HttpClientUtil.doGet(sb.toString());
  }

  @PostMapping("/report/{list}/{roles}/{uid}/{time}/{dateorhour}")
  private Object relistOfDate(@PathVariable String list, @PathVariable String roles, @PathVariable String uid, @PathVariable Long time, @PathVariable String dateorhour) {
    long endTime = time;
    if ("date".equalsIgnoreCase(dateorhour)) {
      endTime += 86400000;
    } else {
      endTime += 3600000;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/report/").append(list).append("/").append(uid).append("/").append(time).append("/").append(endTime);
    return HttpClientUtil.doGet(sb.toString());
  }


  @PostMapping("/report/list/{roles}/{uid}")
  private Object relistOfDate(@PathVariable String roles, @PathVariable String uid) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/report/list/").append(uid);
    return HttpClientUtil.doGet(sb.toString());
  }


  @PostMapping("/detail/{roles}/{id}")
  private Object detail(@PathVariable String roles, @PathVariable String id) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/");
    if ("am".equalsIgnoreCase(roles) || "pm".equalsIgnoreCase(roles)) {
      sb.append("driver/");
    }
    sb.append(roles).append("/detail/").append(id);
    return HttpClientUtil.doGet(sb.toString());
  }

  @PostMapping("/list/{roles}/{uid}/{time}/{dateorhour}")
  private Object listOfDateTime(@PathVariable String roles, @PathVariable String uid, @PathVariable Long time, @PathVariable String dateorhour) {
    long endTime = time;
    if ("date".equalsIgnoreCase(dateorhour)) {
      endTime += 86400000;
    } else {
      endTime += 3600000;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/list/").append(uid).append("/").append(time).append("/").append(endTime);
    return HttpClientUtil.doGet(sb.toString());
  }

  @PostMapping("/list/{roles}/{uid}")
  private Object listOfDate(@PathVariable String roles, @PathVariable String uid) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/list/").append(uid);
    return HttpClientUtil.doGet(sb.toString());
  }

  @PostMapping("/am/list/{roles}/{uid}/{time}")
  private Object amDetail(@PathVariable String roles, @PathVariable String uid, @PathVariable Long time) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/am/list/").append(uid).append("/").append(time);
    return HttpClientUtil.doGet(sb.toString());
  }

  @PostMapping("/am/list/{roles}/{uid}")
  private Object amList(@PathVariable String roles, @PathVariable String uid) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/am/list/").append(uid);
    return HttpClientUtil.doGet(sb.toString());
  }


  @PostMapping("/pm/list/{roles}/{uid}/{time}")
  private Object pmDetail(@PathVariable String roles, @PathVariable String uid, @PathVariable Long time) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/pm/list/").append(uid).append("/").append(time);
    return HttpClientUtil.doGet(sb.toString());
  }

  @PostMapping("/pm/list/{roles}/{uid}")
  private Object pmList(@PathVariable String roles, @PathVariable String uid) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(roles).append("/pm/list/").append(uid);
    return HttpClientUtil.doGet(sb.toString());
  }

  //草稿编辑
  @PostMapping("/draft/update")
  private Object update(@RequestBody JSONObject o) {
    if (null == o || null == o.get("id")) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/draft/update/").append(o.get("id"));
    return HttpClientUtil.doPost(sb.toString(), o);
  }

  //日报保存为草稿
  @PostMapping("/draft/save")
  private String draftSave(@RequestBody JSONObject o) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/draft/commit");
    return HttpClientUtil.doPost(sb.toString(), o);
  }

  //我的草稿箱
  @PostMapping("/draft/list/{uid}/{type}")
  private String myDrafts(@PathVariable String uid, @PathVariable String type) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/draft/list/").append(uid).append("/").append(type);
    return HttpClientUtil.doPost(sb.toString(), null);
  }

  //草稿删除
  @PostMapping("/draft/del/{id}")
  private String draftDel(@PathVariable String id) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/draft/del/").append(id);
    return HttpClientUtil.doPost(sb.toString(), null);
  }
}
